#include "FlashSearch.h"
#include "ComponentsHolder.h"
#include "EndIO.h"
#include <string>

#include <iostream>
using namespace std;
FlashSearch::FlashSearch(double actionTime, ExtentIO* data) :Event(actionTime, data)
{
}

FlashSearch::~FlashSearch(void)
{
}

bool FlashSearch::doAction()
{
	Event * e;
	Cache* cache = ComponentsHolder::getInstance()->getFlashCache();
	EventsHandler* handler = ComponentsHolder::getInstance()->getEventsHandler();
	double actionTime = _actionTime + CacheSearchDelay; // calc action time
	bool foundInFlash = false;
	if (SimulationParameters::flashPolicy == FAST)
	{
		string ioID = cache->getIOID(_data);
		ComponentsHolder::getInstance()->getStatisticsHandler()->extentFetch(ioID);
		if (ComponentsHolder::getInstance()->getFlashDevice()->exist(ioID))
			foundInFlash = true;
	}
	if (foundInFlash || cache->exists(_data))
	{
		ComponentsHolder::getInstance()->getStatisticsHandler()->flashCacheHit();
		_data->hit(); // mark io as hit
	}
	else
	{
		ComponentsHolder::getInstance()->getStatisticsHandler()->miss();
		ComponentsHolder::getInstance()->getCache()->insert(_data);
		if (SimulationParameters::flashPolicy == InsertTOBoth)
			cache->insert(new ExtentIO(*_data));
	}
	e = new EndIO(actionTime, _data);
	handler->addEvent(e);
	return true;
}
